package com.sci99.ex.vm;

import java.util.List;

import org.apache.log4j.Logger;
import org.zkoss.bind.annotation.AfterCompose;
import org.zkoss.bind.annotation.BindingParam;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.NotifyChange;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Window;

import com.sci99.ex.model.Category;
import com.sci99.ex.service.CategoryService;

public class CategoryVM {
	static Logger log = Logger.getLogger(CategoryVM.class);

	private String keyword;
	private List<Category> cateList;
	private Category selectedCate = new Category();

	public List<Category> getCateList() {
		return cateList;
	}

	public void setCateList(List<Category> cateList) {
		this.cateList = cateList;
	}

	public String getKeyword() {
		return keyword;
	}

	public void setKeyword(String keyword) {
		this.keyword = keyword;
	}

	public Category getSelectedCate() {
		return selectedCate;
	}

	public void setSelectedCate(Category selectedCate) {
		this.selectedCate = selectedCate;
	}

	@AfterCompose
	public void doAfterCompose() {
		search();
	}

	@Command
	@NotifyChange("cateList")
	public void search() {
		try {
			cateList = CategoryService.getCategoryList(keyword);
		} catch (Exception e) {
			log.error(e.getMessage());
		}
	}

	@Command
	@NotifyChange("cateList")
	public void edit(@BindingParam("win") Window edWin) {
		edWin.setVisible(true);
		edWin.doModal();
	}

	@Command
	@NotifyChange("cateList")
	public void save(@BindingParam("win") Window edWin) {
		if (edWin != null)
			edWin.setVisible(false);
		try {
			CategoryService.saveCategory(selectedCate);
		} catch (Exception e) {
			Messagebox.show(Msg.DbFail);
			log.error(e.getMessage());
		}
		Messagebox.show(Msg.OptOK);
		search();
	}

	@Command
	@NotifyChange("selectedCate")
	public void add(@BindingParam("win") Window edWin) {
		selectedCate = new Category();
		edWin.setVisible(true);
		edWin.doModal();
	}

	@Command
	@NotifyChange("cateList")
	public void del(@BindingParam("win") Window edWin) {
		if (selectedCate.getId() == null) {
			Messagebox.show("请选择分类");
			return;
		}

		if (Messagebox.show(Msg.CfmDel, null,
				Messagebox.OK + Messagebox.CANCEL, Messagebox.QUESTION) != Messagebox.OK)
			return;
		try {
			CategoryService.delCategory(selectedCate);
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		edWin.setVisible(false);
		search();
	}

	@Command
	@NotifyChange("cateList")
	public void close(@BindingParam("win") Window edWin) {
		edWin.setVisible(false);
		search();
	}

}
